package com.qingcloud.df.executor.service;

import com.qingcloud.df.executor.launcher.process.ComponentExecutorHandle;
import com.qingcloud.df.executor.queue.ComponentMessage;
import com.qingcloud.df.sdk.component.config.ComponentSystemConfig;
import com.qingcloud.df.sdk.component.context.CompInstRuntimeHolder;
import com.qingcloud.df.sdk.component.job.BaseScheduler;
import com.qingcloud.df.sdk.component.transport.akka.AkkaTransporter;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class CollectorJobScheduler extends BaseScheduler {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        CompInstRuntimeHolder runtimeHolder = null;
        String fireTime  = formatter.format(context.getFireTime());
        String nextTime = formatter.format(context.getNextFireTime());
        String beginTime = formatter.format(new Date());
        String endTime = null;
        String jobInstance =  context.getFireInstanceId();
        String status = "1";
        try {
            ComponentSystemConfig componentSystemConfig = (ComponentSystemConfig)context.getJobDetail().getJobDataMap().get("componentSystemConfig");
            log.debug("组件实例id[" + componentSystemConfig.getInstanceId() + "]定时任务开始执行！");
            ComponentMessage message=  new ComponentMessage();
            message.setTopic(componentSystemConfig.getTopic());
            message.setInstanceId(componentSystemConfig.getInstanceId());
            message.setEnv(componentSystemConfig.getEnv());
            ComponentExecutorHandle.fusion(message);
            endTime = formatter.format(new Date());
            log.debug("组件实例id[" + componentSystemConfig.getInstanceId() + "]定时任务执行成功！");
        } catch (Exception e) {
            e.printStackTrace();
            status="0";
        } finally {
            exeRecord(fireTime, nextTime, beginTime, endTime, jobInstance, status);
            if(runtimeHolder!=null) {
                CompInstRuntimeHolder.removeContext();
            }
        }
    }

    @Override
    public void exeRecord(String fireTime, String nextTime, String beginTime, String endTime, String jobInstance, String status) {
        log.debug(fireTime+"--"+nextTime+"--"+beginTime+"--"+endTime+"--"+status);
    }
}
